package com.jt.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Configuration
@PropertySource("classpath:/properties/redis.properties")
public class JedisConfig {

    /**
     * 1，单台redis服务器
     */
    @Value("${redis.host}")
    private String host;
    @Value("${redis.port}")
    private Integer port;

    @Bean
    public Jedis jedis(){
        return new Jedis(host,port);
    }

    /**
     * 2，redis分片机制
     */
    @Value("${redis.nodes}")
    private String nodes;

    @Bean
    public ShardedJedis shardedRedis(){
        nodes = nodes.trim();
        List<JedisShardInfo> shards = new ArrayList<>();
        String[] nodeArray = nodes.split(",");
        //strNode = host:port
        for (String strNode : nodeArray){
            String host = strNode.split(":")[0];
            int port = Integer.parseInt(strNode.split(":")[1]);
            JedisShardInfo info = new JedisShardInfo(host, port);
            shards.add(info);
        }
        return new ShardedJedis(shards);
    }

    /**
     * 3，redis哨兵机制
     */
//    @Value("${redis.sentinel}")
//    private String sentinel;
//    @Bean
//    public JedisSentinelPool jedisSentinelPool(){
//        sentinel = sentinel.trim();
//        Set<String> sentinels = new HashSet<>();
//        sentinels.add(sentinel);
//        return new JedisSentinelPool("mymaster", sentinels);
//    }


    /**
     * 4，redis集群
     */
    @Value("${redis.clusters}")
    private String clusters;

    @Bean
    public JedisCluster jedisCluster(){
        clusters = clusters.trim();
        Set<HostAndPort> set = new HashSet<>();
        String[] clusterArray = clusters.split(",");
        for (String strCluster :clusterArray) {
            String host = strCluster.split(":")[0];
            int port = Integer.parseInt(strCluster.split(":")[1]);
            HostAndPort hostAndPort = new HostAndPort(host, port);
            set.add(hostAndPort);
        }

        return new JedisCluster(set);
    }



}
